package com.milling.web.core.config;

import com.milling.common.utils.scanner.SocketListener;
import com.milling.web.utils.ConfigScanner;
import com.milling.web.utils.InstockScanner;
import com.milling.web.utils.SortingScanner;
import com.milling.web.utils.StorageScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.PostConstruct;
import java.net.Socket;

@Configuration
public class ScannerInitializerConfig {

    @Value("${scanner.storage.ip:192.168.237.66}")
    private String storageIp;

    @Value("${scanner.storage.port:2001}")
    private int storagePort;

    @Value("${scanner.config.ip:192.168.237.77}")
    private String configIp;

    @Value("${scanner.config.port:2001}")
    private int configPort;

    @Value("${scanner.sorting.ip:192.168.237.149}")
    private String sortingScannerIp;

    @Value("${scanner.sorting.instockip:192.168.237.148}")
    private String instockIp;

    @Value("${scanner.sorting.port:2001}")
    private int sortingScannerPort;

    @Autowired
    @Lazy
    private StorageScanner storageScanner;

    @Autowired
    @Lazy
    private ConfigScanner configScanner;

    @Autowired
    @Lazy
    private SortingScanner sortingScanner;

    @Autowired
    @Lazy
    private InstockScanner instockScanner;

    @Configuration
    @ConditionalOnProperty(name = "mac.type", havingValue = "1")
    public static class Type1Initializer {

        private final ScannerInitializerConfig config;

        public Type1Initializer(ScannerInitializerConfig config) {
            this.config = config;
        }

        @PostConstruct
        public void init() {
            initSocket(config);
        }

        private void initSocket(ScannerInitializerConfig config) {
            int maxRetries = 3;
            long retryInterval = 5000;

            // 初始化存储扫码器
            boolean storageConnected = false;
            for (int i = 0; i < maxRetries && !storageConnected; i++) {
                try {
                    Socket socket = new Socket(config.storageIp, config.storagePort);
                    SocketListener listener = new SocketListener(socket, config.storageScanner);
                    new Thread(listener).start();
                    storageConnected = true;
                    System.out.println("  初始化缓存库入库扫码器完成     ");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[缓存库入库扫码器]尝试重新连接缓存库入库扫码器... 第 " + (i + 1) + " 次重试");
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
            if (!storageConnected) {
                System.out.println("存储扫码器连接失败，已达到最大重试次数");
            }

            // 初始化配置扫码器
            boolean configConnected = false;
            for (int i = 0; i < maxRetries && !configConnected; i++) {
                try {
                    Socket socket2 = new Socket(config.configIp, config.configPort);
                    SocketListener listener2 = new SocketListener(socket2, config.configScanner);
                    new Thread(listener2).start();
                    configConnected = true;
                    System.out.println("  初始化配针扫码器完成     ");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[配针扫码器]尝试重新连接配置扫码器... 第 " + (i + 1) + " 次重试");
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
            if (!configConnected) {
                System.out.println("配针扫码器连接失败，已达到最大重试次数");
            }
        }
    }

    @Configuration
    @ConditionalOnProperty(name = "mac.type", havingValue = "2")
    public static class Type2Initializer {

        private final ScannerInitializerConfig config;

        public Type2Initializer(ScannerInitializerConfig config) {
            this.config = config;
        }

        @PostConstruct
        public void init() {
            initSocketSorting();
        }

        private void initSocketSorting() {
            int maxRetries = 3;
            long retryInterval = 5000;

            // 初始化分拣机扫码器
            boolean sortingConnected = false;
            for (int i = 0; i < maxRetries && !sortingConnected; i++) {
                try {
                    Socket socket = new Socket(config.sortingScannerIp, config.sortingScannerPort);
                    SocketListener listener = new SocketListener(socket, config.sortingScanner);
//                    SocketListener listener = new SocketListener(socket,
//                            new SortingScanner(config.sortingScannerIp, config.sortingScannerPort));
                    new Thread(listener).start();
                    sortingConnected = true;
                    System.out.println("  初始化分拣扫码器完成     ");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[分拣扫码器]尝试重新连接分拣扫码器... 第 " + (i + 1) + " 次重试");
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
            if (!sortingConnected) {
                System.out.println("分拣扫码器连接失败，已达到最大重试次数");
            }

            // 初始化入库扫码器
            boolean instockConnected = false;
            for (int i = 0; i < maxRetries && !instockConnected; i++) {
                try {
                    Socket socket2 = new Socket(config.instockIp, config.sortingScannerPort);
                    SocketListener listener2 = new SocketListener(socket2, config.instockScanner);
                    new Thread(listener2).start();
                    instockConnected = true;
                    System.out.println("  初始化入库扫码器完成     ");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[入库扫码器]尝试重新连接入库扫码器... 第 " + (i + 1) + " 次重试");
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
            if (!instockConnected) {
                System.out.println("入库扫码器连接失败，已达到最大重试次数");
            }

        }
    }
}
